// facility/map/map.js
import http from '../../http'
import gcoord from 'gcoord'
import {
	handleTree
} from "../../libs/tool";
let FormData = require('../../components/formData/formData.js')
Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		top: '',
		left: '',
		height: '',
		width: '',

		facilityNum: {
			lamp: 0,
			gateway: 0,
			screen: 0,
			camera: 0,
			Audio: 0,
			monitoring: 0,
			loop: 0,
			sensor:0
		}, //各个设备数量
		statusNum: {
			onOpen: 0,
			onOff: 0,
			closeOn: 0,
			closeOff: 0,
			notActivated: 0
		}, //设备状态数量

		projectInfo: {}, //跳转的有chilren的项目信息

		markers: [],
		latitude: '',
		longitude: '',
		scale: 18,
		rgcData: {},

		facilityList: [], //设备列表
		facilityInfoBol: false, //设备详情
		deviceMetadata: [],

		nowProjectInfo: {}, //当前项目(分组)信息
		nowfacilityInfo: {}, // 当前设备信息
		infoType: 'project', // 判断当前显示项目还是设备

		// 下发策略
		strategyList: [],
		strategyBol: false,


		facilitySelect: false, //设备切换
		facilityName: '', //当前设备

		projectBol: false, //项目切换
	},
	markerArray(arr, AudioList) {
		let list = arr.filter(item => {
			return item.deviceStatusList.length != 0
		})
		list = list.map(item => {
			if (item.deviceStatusList.length == 1) {
				item.deviceStatusList[0].longitude = item.longitude
				item.deviceStatusList[0].latitude = item.latitude
			} else {
				item.deviceStatusList.forEach((Item, Index) => {
					Item.longitude = item.longitude + (0.00007 * Index)
					Item.latitude = item.latitude + (0.00005 * Index)
				});
			}
			return item.deviceStatusList
		})
		let facilityList = []
		list.forEach(item => {
			facilityList = [...facilityList, ...item]
		})
		// 音柱
		if (AudioList) {
			facilityList.forEach(item => {
				item.deviceStatus = -1
				AudioList.forEach(Item => {
					if (item.sn == Item.device_seed) {
						item.deviceStatus = Item.status == 1 ? 5 : 8
						item.audioId = Item.id
					}
				})
			})
		}
		facilityList = facilityList.map(item => {
			let iconPath = ''
			if (this.data.facilityName == 'lamp,gateway') {
				iconPath = 'light'
			} else if (this.data.facilityName == 'screen') {
				iconPath = 'screen'
			} else if (this.data.facilityName == 'camera') {
				iconPath = 'camera'
			} else if (this.data.facilityName == 'Audio') {
				iconPath = 'audio'
			} else if (this.data.facilityName == 'loop') {
				iconPath = 'loop'
			} else if (this.data.facilityName == 'sensor') {
				iconPath = 'sensor'
			} else if (this.data.facilityName == 'monitoring' && item.product == 10) {
				iconPath = 'water'
			} else if (this.data.facilityName == 'monitoring' && item.product == 11) {
				iconPath = 'environment'
			}
			item.longitude = this.coord([item.longitude, item.latitude])[0]
			item.latitude = this.coord([item.longitude, item.latitude])[1]
			item.iconPath = item.deviceStatus == 5 ? '../../img/' + iconPath + '/on-open.png' : item.deviceStatus == 6 ? '../../img/' + iconPath + '/on-close.png' : item.deviceStatus == 7 ? '../../img/' + iconPath + '/off-open.png' : item.deviceStatus == 8 ? '../../img/' + iconPath + '/off-close.png' : item.deviceStatus == -1 ? '../../img/' + iconPath + '/not-activated.png' : '../../img/' + iconPath + '/off-close.png'
			item.iconTapPath = '../../img/marker_red.png'
			item.width = 20
			item.height = 20
			item.id = Number(item.id)
			item.zIndex = 100
			item.callout = {
				display: 'BYCLICK',
				content: item.name,
				padding: 5,
				borderRadius: 10
			}
			return item
		})
		console.log(facilityList);
		this.setData({
			facilityList: facilityList
		})
		this.setStatusNum(facilityList)
		return facilityList
	},
	coord(location) {
		var result = gcoord.transform(
			location, // 经纬度坐标
			gcoord.BD09, // 当前坐标系
			gcoord.GCJ02 // 目标坐标系
		);
		return result
	},
	setStatusNum(arr) {
		let onOpen = arr.filter(item => {
			return item.deviceStatus == 5
		})
		let onOff = arr.filter(item => {
			return item.deviceStatus == 6
		})
		let closeOn = arr.filter(item => {
			return item.deviceStatus == 7
		})

		let closeOff = arr.filter(item => {
			return item.deviceStatus != 5 && item.deviceStatus != 6 && item.deviceStatus != 7 && item.deviceStatus != -1
		})
		let notActivated = arr.filter(item => {
			return item.deviceStatus == -1
		})

		this.setData({
			statusNum: {
				onOpen: onOpen.length,
				onOff: onOff.length,
				closeOn: closeOn.length,
				closeOff: closeOff.length,
				notActivated: notActivated.length
			}
		})
	},
	timeChange(time) {
		const date = new Date(time);
		const formattedDate = date.toLocaleString();
		console.log(formattedDate);
		return formattedDate
	},
	mapTap() {
		this.setData({
			infoType: 'project'
		})
	},
	// 返回
	back() {
		this.setData({
			facilityName: ''
		})
		wx.navigateBack({
			delta: 1
		});
	},
	// 搜索
	searchBtn() {
		if (this.data.search.trim() != '') {
			let list = this.data.markers.filter(item => {
				return item.sn == this.data.search.trim()
			})
			if (list.length != 0) {
				this.setData({
					latitude: list[0].latitude,
					longitude: list[0].longitude,
					scale: 22,
				})
			} else {
				wx.showToast({
					title: '项目下没有该设备',
					icon: 'error',
				})
			}
		}


	},
	// 点击maker
	makertap(value) {
		console.log(value.markerId,'点击maker');
		this.data.facilityList.forEach(item => {
			if (item.id == value.markerId) {
				console.log('设备信息', item);
				setTimeout(() => {
					this.setData({
						nowfacilityInfo: item,
						infoType: 'facility'
					})
				}, 100);
			}
		})
	},
	// 详情
	details() {
		if (this.data.infoType == 'project') {
			wx.showToast({
				title: '请选择设备后查看',
				icon: 'error',
			})
		} else {
			wx.showLoading({
				title: '加载中...'
			});
			http.get({
				url: '/zg/device-instance/get',
				data: {
					id: this.properties.nowfacilityInfo.id
				},
				then: (res) => {
					console.log('设备信息', res);
					let data = res.data.data
					let info = this.data.nowfacilityInfo
					info.lightName = data.lightName

					function isJSON(str) {
						try {
							JSON.parse(str);
							return true;
						} catch (e) {
							return false;
						}
					}
					this.setData({
						nowfacilityInfo: info,
						deviceMetadata: isJSON(data.deviceMetadata) ? JSON.parse(data.deviceMetadata) : []
					}, () => {
						wx.hideLoading()
						this.setData({
							facilityInfoBol: true
						});
					})
				}
			})
			// 监控设备
			if (
				this.data.facilityName == 'monitoring'
			) {
				http.get({
					url: '/zg/iot-links/data/latest/' + this.data.nowfacilityInfo.id,
					then: (res) => {
						console.log('监控设备信息', res);
						this.setData({
							deviceMetadata: res.data ? res.data : []
						}, () => {
							wx.hideLoading()
							this.setData({
								facilityInfoBol: true
							});
						})
					}
				})
			}
		}
	},
	copyText(e) {
		console.log(e);
		let data = e.currentTarget.dataset.value
		wx.setClipboardData({
			data: data,
			success: (res) => {
				console.log(res);
			}
		})
	},
	historyInfo(){
		wx.navigateTo({
			url: `../historyInfo/historyInfo?id=${this.properties.nowfacilityInfo.id}`,
		})
	},
	facilityInfoClose() {
		this.setData({
			facilityInfoBol: false
		});
	},
	// 下发策略
	strategy() {
		http.get({
			url: '/zg/strategy/page',
			data: {
				pageNo: 1,
				pageSize: 20
			},
			then: (res) => {
				console.log('策略列表', res);
				let list = res.data.data.list.map(item => {
					return {
						value: item.id,
						disabled: item.status == 0 ? false : true,
						text: item.name
					}
				})
				this.setData({
					strategyList: list,
					strategyBol: true,
				});
			}
		})
	},
	strategyConfirm(event) {
		wx.showLoading({
			title: '加载中...'
		});
		console.log(event.detail);
		http.get({
			url: '/zg/strategy/get',
			data: {
				id: event.detail.value.value
			},
			then: (res) => {
				console.log('策略信息', res);
				let data = res.data.data
				let list = []
				if (data.projectId != '') {
					list = data.projectId.split(',')
				}
				let bol = list.filter(item => {
					return item == this.data.nowProjectInfo.id
				})
				if (bol.length == 0) {
					list = [this.data.nowProjectInfo.id, ...list]
					http.post({
						url: '/zg/command/strategy',
						data: {
							projectIds: list,
							strategyTaskList: data.strategyTaskList,
							command: "STRATEGY",
							projectGroup: this.data.nowProjectInfo.type == 0 ? 0 : 1,
							strategyId: data.id
						},
						then: (res) => {
							if (res.data.code == 0) {
								wx.showToast({
									title: '下发成功',
									icon: 'success',
								})
								this.gain()
								this.setData({
									strategyBol: false
								});
							}
						}
					})
				} else {
					wx.showToast({
						title: '策略已下发该项目',
						icon: 'error',
					})
				}
			}
		})
	},
	strategyClose() {
		this.setData({
			strategyBol: false
		});
	},


	// 项目选择
	projectShow() {
		this.setData({
			projectBol: true
		});
	},
	projectClose() {
		this.setData({
			projectBol: false
		});
	},
	projectCut(event) {
		wx.showLoading({
			title: '加载中...'
		});
		console.log(event.currentTarget.dataset);
		let data = event.currentTarget.dataset
		this.setData({
			nowProjectInfo: {
				name: data.info.projectName,
				id: data.info.id,
				type: data.info.parentId
			},
			longitude: this.coord([data.info.longitude, data.info.latitude])[0],
			latitude: this.coord([data.info.longitude, data.info.latitude])[1],
			scale: 18,
			projectBol: false,
			infoType: 'project'
		}, () => {
			this.gain()
		})
	},
	// 设备选择
	facilitySelectShow() {
		this.setData({
			facilitySelect: true
		});
	},
	facilitySelectClose() {
		this.setData({
			facilitySelect: false
		});
	},
	facilityCut(event) {
		wx.showLoading({
			title: '加载中...'
		});
		console.log(event.currentTarget.dataset);
		let data = event.currentTarget.dataset
		this.setData({
			facilityName: data.name,
			facilitySelect: false,
			infoType: 'project',
		}, () => {
			this.gain()
		})
	},
	// 定位自身位置
	selfPositioning() {
		wx.getLocation({
			type: "gcj02",
			success: (res) => {
				console.log(res);
				this.setData({
					longitude: res.longitude,
					latitude: res.latitude
				})
			},
			fail(error) {
				console.log(error);
			}
		})
	},
	gain() {
		let params = {
			pageNo: 1,
			pageSize: -1,
			categoryId: this.data.facilityName,
		}
		if (this.data.nowProjectInfo.type == 0) {
			params.projectId = this.data.nowProjectInfo.id
		} else {
			params.group = this.data.nowProjectInfo.id
		}
		http.get({
			url: '/zg/light-pole/mapPage',
			data: params,
			then: (res) => {
				console.log('灯杆设备列表', res);
				if (this.data.facilityName == 'Audio') {
					var formData = new FormData();
					formData.append("username", "wzn");
					formData.append("passwd", "wzn123456");
					let newData = formData.getData();
					http.post({
						prefix: '/xxbs',
						url: "/user/gtoken",
						header: {
							'content-type': newData.contentType
						},
						data: newData.buffer,
						then: (Res) => {
							console.log('音柱登录', Res);
							http.post({
								url: '/zg/audio/listdev',
								then: (Res) => {
									console.log('音柱列表', Res);
									this.setData({
										markers: this.markerArray(res.data.data, Res.data.devlist),
									}, () => {
										wx.hideLoading()
									})
								}
							})
						}
					})
				} else {
					this.setData({
						markers: this.markerArray(res.data.data, false),
					}, () => {
						wx.hideLoading()
					})
				}
			}
		})
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad(options) {
		console.log(options);

	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow() {
		wx.showLoading({
			title: '加载中...'
		});
		this.setData({
			top: wx.getStorageSync('customTop'),
			left: wx.getStorageSync('screenWidth') - wx.getStorageSync('customRight'),
			height: wx.getStorageSync('customHeight'),
			width: wx.getStorageSync('customLeft'),
		})
		// 从主页进入地图
		if (this.data.facilityName == '') {
			let pages = getCurrentPages()
			let currentPage = pages[pages.length - 1]
			let options = currentPage.options
			http.get({
				url: '/zg/project/get',
				data: {
					id: options.projectId,
				},
				then: (res) => {
					console.log('项目(分组)信息', res);
					this.setData({
						nowProjectInfo: {
							name: res.data.data.projectName,
							id: res.data.data.id,
							type: res.data.data.parentId
						},
						longitude: this.coord([res.data.data.longitude, res.data.data.latitude])[0],
						latitude: this.coord([res.data.data.longitude, res.data.data.latitude])[1],
					})
					http.get({
						url: '/zg/project/list',
						data: {
							countType: 'lightpole',
						},
						then: (Res) => {
							console.log('所有项目信息', Res);
							let list = handleTree(Res.data.data, "id", "parentId");
							list.forEach(item => {
								if (item.id == options.projectId) {
									console.log(item);
									this.setData({
										projectInfo: item
									})
								}
							})
							http.post({
								url: '/zg/iot-links/index/lineChart',
								data: {
									projectId: options.projectId,
									property: "power",
								},
								then: (res) => {
									console.log("设备数量", res.data);
									let facilityNum = res.data.data.info
									this.setData({
										facilityNum: facilityNum ? facilityNum : {
											lamp: 0,
											gateway: 0,
											screen: 0,
											camera: 0,
											Audio: 0,
											monitoring: 0,
											loop: 0,
											sensor:0
											
										}
									})
									let list = []
									for (const key in facilityNum) {
										list = [{
											name: key,
											num: facilityNum[key]
										}, ...list]
									}
									list = list.filter(item => {
										return item.num != 0
									})
									let lampBol = list.filter(item => {
										return item.name == 'lamp' || item.name == 'gateway'
									})
									console.log('设备数量', list);
									if (list.length != 0) {
										this.setData({
											facilityName: lampBol.length != 0 ? 'lamp,gateway' : list[0].name
										}, () => {
											this.gain()
										})
									} else {
										this.setData({
											facilityName: ''
										}, () => {
											wx.showToast({
												title: '该项目下没有设备',
												icon: 'error',
											})
										})
									}
								}
							})
						}
					})
				}
			})
		} else {
			this.gain()
		}
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage() {

	}
})